import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'


NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist


router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  // 判断用户是否已登录
  const hasToken = getToken()
  if (hasToken) { //登录状态
    if (to.path === '/login') {
      // 登录状态去登录界面直接重定向去首页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.refreshPage
      if (!hasGetUserInfo) {
        next()
      } else {
        // get user info
        const { routers } = await store.dispatch('user/getInfo')
        const accessRoutes = await store.dispatch('permission/generateRoutes', routers)
        // console.log(accessRoutes);
        console.log('打印路由权限',accessRoutes);

        router.options.routes = accessRoutes
        router.addRoutes(accessRoutes)
        router.addRoutes([{ path: '*', redirect: '/404', hidden: true }])
        next({ ...to, replace: true })
      }
    }
  } else {
    //  未登录
    if (whiteList.indexOf(to.path) !== -1) {
      // 去登录界面
      next()
    } else {
      // 其他页面没有许可进入，重定向去登录
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
